#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# --
# --
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Date: 2021/4/14 11:13
# Email lmay@lmaye.com
# ----------------------------------------------------------
import datetime
import os

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QGroupBox, QFormLayout, QWidget, QGridLayout, QPushButton, \
    QListWidget, QLabel, QFileDialog, QLineEdit, QRadioButton, QTextEdit

from core.handler.sync_handler import SyncThread


class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.initQMainWindow()

    def initQMainWindow(self):
        """
            初始化界面

            :return:
        """
        self.creatFormGroupBox()
        self.createGridGroupBox()
        main_layout = QVBoxLayout()
        hbox_layout = QHBoxLayout()
        hbox_layout.addWidget(self.gb2)
        main_layout.addWidget(self.gb1)
        main_layout.addLayout(hbox_layout)
        self.setLayout(main_layout)
        self.setFixedSize(640, 520)
        self.setWindowTitle("Excel 数据处理")
        self.setWindowIcon(QIcon("./favicon.ico"))

    def creatFormGroupBox(self):
        """
            UI 日志输出区域

            :return:
        """
        self.gb1 = QGroupBox("输出区域")
        fl = QFormLayout()
        self.gb1_lw = QListWidget()
        self.gb1_lw.setFixedSize(600, 270)
        fl.addRow(self.gb1_lw)
        self.gb1.setLayout(fl)

    def createGridGroupBox(self):
        """
             操作区域

            :return:
        """
        self.gb2 = QGroupBox("Excel 操作区域")
        gl = QGridLayout()

        l1 = QLabel("Excel目录:")
        self.l1_le = QLineEdit()
        self.l1_le.setReadOnly(True)
        self.l1_le.setPlaceholderText("处理目录")
        bt1 = QPushButton("选择")
        bt1.clicked.connect(self.changeDir1)

        l2 = QLabel("生成目录:")
        self.l2_le = QLineEdit()
        self.l2_le.setReadOnly(True)
        self.l2_le.setPlaceholderText("存放目录")
        bt2 = QPushButton("选择")
        bt2.clicked.connect(self.changeDir2)

        l3 = QLabel("取数文件:")
        self.l3_le = QLineEdit()
        self.l3_le.setReadOnly(True)
        self.l3_le.setPlaceholderText("取数据的Excel文件")
        bt3 = QPushButton("选择")
        bt3.clicked.connect(self.changeFile)

        l4 = QLabel("条件列名:")
        self.l4_le = QLineEdit()
        self.l4_le.setText("")
        self.l4_le.setPlaceholderText("关联条件的列名")

        l5 = QLabel("数据列名:")
        self.l5_qe = QTextEdit()
        self.l5_qe.setText("")
        self.l5_qe.setPlaceholderText("多个列名用,逗号隔开")

        l6 = QLabel("插入列名:")
        self.l6_qe = QTextEdit()
        self.l6_qe.setText("")
        self.l6_qe.setPlaceholderText("多个列名用,逗号隔开")

        l7 = QLabel("生成类型:")
        self.l7_rb1 = QRadioButton(self)
        self.l7_rb1.setText("csv")
        self.l7_rb1.setChecked(True)
        self.l7_rb2 = QRadioButton(self)
        self.l7_rb2.setText("xlsx")

        bt4 = QPushButton("数据处理")
        bt4.clicked.connect(self.execute)
        # 第一排布局
        hbl1_1 = QHBoxLayout()
        hbl1_1.addWidget(l1)
        hbl1_1.addWidget(self.l1_le)
        hbl1_1.addWidget(bt1)
        gl.addLayout(hbl1_1, 0, 0)

        hbl1_2 = QHBoxLayout()
        hbl1_2.addWidget(l2)
        hbl1_2.addWidget(self.l2_le)
        hbl1_2.addWidget(bt2)
        gl.addLayout(hbl1_2, 0, 1)

        # 第二排布局
        hbl2_1 = QHBoxLayout()
        hbl2_1.addWidget(l3)
        hbl2_1.addWidget(self.l3_le)
        hbl2_1.addWidget(bt3)
        gl.addLayout(hbl2_1, 1, 0)

        hbl2_2 = QHBoxLayout()
        hbl2_2.addWidget(l4)
        hbl2_2.addWidget(self.l4_le)
        gl.addLayout(hbl2_2, 1, 1)
        # 第三排布局
        hbl3_1 = QHBoxLayout()
        hbl3_1.addWidget(l5)
        hbl3_1.addWidget(self.l5_qe)
        gl.addLayout(hbl3_1, 2, 0)

        hbl3_2 = QHBoxLayout()
        hbl3_2.addWidget(l6)
        hbl3_2.addWidget(self.l6_qe)
        gl.addLayout(hbl3_2, 2, 1)
        # 第四排布局
        hbl4_1 = QHBoxLayout()
        hbl4_1.addWidget(l7)
        hbl4_1.addWidget(self.l7_rb1)
        hbl4_1.addWidget(self.l7_rb2)
        gl.addLayout(hbl4_1, 3, 0)

        hbl4_2 = QHBoxLayout()
        hbl4_2.addWidget(bt4)
        gl.addLayout(hbl4_2, 3, 1)
        self.gb2.setLayout(gl)

    def changeDir1(self):
        """
            文件选择器

            :return:
        """
        directory = QFileDialog.getExistingDirectory(self)
        if not directory:
            return
        self.printMsg("{} 选中目录: {}".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), directory))
        self.l1_le.setText(directory)

    def changeDir2(self):
        """
            文件选择器

            :return:
        """
        directory = QFileDialog.getExistingDirectory(self)
        if not directory:
            return
        self.printMsg("{} 选中目录: {}".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), directory))
        self.l2_le.setText(directory)

    def changeFile(self):
        """
            文件选择器

            :return:
        """
        file_name, file_type = QFileDialog.getOpenFileName(self, "选取文件", os.getcwd(), "All Files(*);;Excel Files(*.xlsx)")
        if not file_name:
            return
        self.printMsg("{} 选中文件: {}".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), file_name))
        self.l3_le.setText(file_name)

    def printMsg(self, log):
        """
            界面打印日志

            :param log: 日志
            :return:
        """
        self.gb1_lw.addItem(log)
        # 自动滚动
        self.gb1_lw.setCurrentRow(self.gb1_lw.count() - 1)

    def execute(self):
        """
            执行处理信号槽

            :return:
        """
        cr_type = self.l7_rb1.text()
        if self.l7_rb2.isChecked():
            cr_type = self.l7_rb2.text()
        int_path = self.l1_le.text().strip()
        out_path = self.l2_le.text().strip()
        take_file = self.l3_le.text().strip()
        if not int_path:
            self.printMsg("{} 请选择要解析的文件目录...".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
            return
        if not out_path:
            self.printMsg("{} 请选择要存储的文件目录...".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
            return
        # if not take_file:
        #     self.printMsg("{} 请选择要取数据的文件...".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
        #     return
        where_columns = self.l4_le.text().replace(" ", "")
        # if len(where_columns) <= 0:
        #     self.printMsg("{} 请填写关联条件的列名...".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
        #     return
        source_columns = self.l5_qe.toPlainText().replace(" ", "")
        if len(source_columns) <= 0:
            self.printMsg("{} 请填写数据的列名...".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
            return
        add_columns = self.l6_qe.toPlainText().replace(" ", "")
        # if len(add_columns) <= 0:
        #     self.printMsg("{} 请填写插入的列名...".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
        #     return
        self.t3 = SyncThread()
        self.t3.set_param(int_path, out_path, take_file, cr_type, where_columns, source_columns, add_columns)
        self.t3.signal_out.connect(self.printMsg)
        self.t3.start()
